\defmodule {PrintfFormat}

This class acts like a \class{StringBuffer} which defines new types
of \texttt{append} methods.
It defines certain functionalities of the ANSI C \texttt{printf}
function that also can be accessed through static methods.
The information given here is strongly inspired
from the \texttt{man} page of the C \texttt{printf} function.

Most methods of this class format numbers for the English US
locale only. One can use the Java class \externalclass{java.util}{Formatter}
for performing locale-independent formatting.

\bigskip\hrule

\begin{code}
\begin{hide}
/*
 * Class:        PrintfFormat
 * Description:
 * Environment:  Java
 * Software:     SSJ
 * Copyright (C) 2001  Pierre L'Ecuyer and Universite de Montreal
 * Organization: DIRO, Universite de Montreal
 * @author
 * @since

 * SSJ is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License (GPL) as published by the
 * Free Software Foundation, either version 3 of the License, or
 * any later version.

 * SSJ is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * A copy of the GNU General Public License is available at
   <a href="http://www.gnu.org/licenses">GPL licence site</a>.
 */
\end{hide}
package umontreal.iro.lecuyer.util; \begin{hide}

import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.util.Formatter;
\end{hide}


public class PrintfFormat implements CharSequence, Appendable\begin{hide} {
   private static NumberFormat nf = NumberFormat.getInstance (Locale.US);
   private static DecimalFormatSymbols dfs =
       new DecimalFormatSymbols (Locale.US);
   private static final int NDEC = 50;
   private static DecimalFormat[] dfe = new DecimalFormat[NDEC+1];
   private static DecimalFormat[] dfg = new DecimalFormat[NDEC+1];
   private StringBuffer sb;
/*
   private static void round (int b, StringBuffer num) {
      // round a real number up if it is >= 0.5
      // base is b

      // round up the fractional part
      int j = num.length() - 1;
      String bm1 = String.valueOf (b - 1);
      while (j >= 0 && num.charAt(j) == bm1.charAt(0)) {
         num.deleteCharAt(j);
         j--;
      }

      char c;
      if (j < 0)
         return;
      if (num.charAt(j) != '.') {
         c = num.charAt(j);
         ++c;
         num.replace(j, j + 1, Character.toString(c));
         return;
      }

      // round up the integral part
      j--;
      while (j >= 0 && num.charAt(j) == bm1.charAt(0)) {
         num.replace(j, j + 1, "0");
         j--;
      }

     if (j < 0 || num.charAt(j) == '-') {
         num.insert( j + 1, '1');
     } else if (num.charAt(j) == ' ') {
         num.replace(j, j + 1, "1");
     } else {
         c = num.charAt(j);
         ++c;
         num.replace(j, j + 1, Character.toString(c));
      }
  }*/ \end{hide}
\end{code}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Constants}

\begin{code}

   public static final String NEWLINE\begin{hide} =
               System.getProperty("line.separator");\end{hide}
\end{code}
\begin{tabb} End-of-line symbol or line separator. It is ``$\backslash$n''
 for Unix/Linux, ``$\backslash$r$\backslash$n" for MS-DOS/MS-Windows, and
  ``$\backslash$r'' for Apple OSX.
\end{tabb}
\begin{code}

   public static final String LINE_SEPARATOR\begin{hide} =
               System.getProperty("line.separator");\end{hide}
\end{code}
\begin{tabb} End-of-line symbol or line separator. Same as \texttt{NEWLINE}.
\end{tabb}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Constructors}
\begin{code}

   public PrintfFormat()\begin{hide} {
      sb = new StringBuffer();
   }\end{hide}
\end{code}
\begin{tabb}  Constructs a new buffer object containing an empty string.
\end{tabb}
\begin{code}

   public PrintfFormat (int length)\begin{hide} {
      sb = new StringBuffer (length);
   }\end{hide}
\end{code}
\begin{tabb}  Constructs a new buffer object with an initial capacity of \texttt{length}.
\end{tabb}
\begin{htmlonly}
   \param{length}{initial length of the buffer}
\end{htmlonly}
\begin{code}

   public PrintfFormat (String str)\begin{hide} {
      sb = new StringBuffer (str);
   }\end{hide}
\end{code}
\begin{tabb}  Constructs a new buffer object containing the initial string \texttt{str}.
\end{tabb}
\begin{htmlonly}
   \param{str}{initial contents of the buffer}
\end{htmlonly}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Methods}
\begin{code}

   public PrintfFormat append (String str)\begin{hide} {
      sb.append (str);
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Appends \texttt{str} to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{str}{string to append to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, String str)\begin{hide} {
      sb.append (s (fieldwidth, str));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{s}{int,String} static method to append \texttt{str} to the buffer.
   A minimum of \texttt{fieldwidth} characters will be used.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum number of characters that will be added to the buffer}
   \param{str}{string to append to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (double x)\begin{hide} {
      sb.append (x);
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Appends \texttt{x} to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{x}{value being added to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, double x)\begin{hide} {
      sb.append (f (fieldwidth, x));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{f}{int,double} static method to append \texttt{x} to the buffer.
   A minimum of \texttt{fieldwidth} characters will be used.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the converted string to be appended}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, int precision, double x)\begin{hide} {
      sb.append (f (fieldwidth, precision, x));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{f}{int,int,double} static method to append \texttt{x} to the buffer.
   A minimum of \texttt{fieldwidth} characters will be used with the given \texttt{precision}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the converted string to be appended}
   \param{precision}{number of digits after the decimal point of the converted value}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int x)\begin{hide} {
      sb.append (x);
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Appends \texttt{x} to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, int x)\begin{hide} {
      sb.append (d (fieldwidth, x));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{d}{int,long} static method to append \texttt{x} to the buffer.
   A minimum of \texttt{fieldwidth} characters will be used.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the converted string to be appended}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (long x)\begin{hide} {
      sb.append (x);
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Appends \texttt{x} to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, long x)\begin{hide} {
      sb.append (d (fieldwidth, x));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{d}{int,long} static method to append \texttt{x} to the buffer.
   A minimum of \texttt{fieldwidth} characters will be used.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the converted string to be appended}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (int fieldwidth, int accuracy, int precision,
                               double x)\begin{hide} {
      sb.append (format (fieldwidth, accuracy, precision, x));
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Uses the \method{format}{int,int,int,double}
   static method with the same four arguments to append \texttt{x} to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the converted string to be appended}
   \param{accuracy}{number of digits after the decimal point}
   \param{precision}{number of significant digits}
   \param{x}{value to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public PrintfFormat append (char c)\begin{hide} {
      sb.append (c);
      return this;
   }\end{hide}
\end{code}
\begin{tabb}   Appends a single character to the buffer.
\end{tabb}
\begin{htmlonly}
   \param{c}{character to be appended to the buffer}
   \return{this object}
\end{htmlonly}
\begin{code}

   public void clear()\begin{hide} {
      sb.setLength (0);
   }\end{hide}
\end{code}
\begin{tabb}   Clears the contents of the buffer.
\end{tabb}
\begin{code}

   public StringBuffer getBuffer()\begin{hide} {
      return sb;
   }\end{hide}
\end{code}
\begin{tabb}   Returns the \class{StringBuffer} associated with that object.
\end{tabb}
\begin{htmlonly}
   \return{the internal \class{StringBuffer} object}
\end{htmlonly}
\begin{code}

   public String toString()\begin{hide} {
      return sb.toString();
   }\end{hide}
\end{code}
\begin{tabb}   Converts the buffer into a \class{String}.
\end{tabb}
\begin{htmlonly}
   \return{the \class{String} conversion of the internal buffer}
\end{htmlonly}
\begin{code}

   public static String s (String str)\begin{hide} {
      if (str == null)
         return "null";
      else
         return str;
   }\end{hide}
\end{code}
\begin{tabb}
   Same as \method{s}{int,String}~\texttt{(0, str)}. If the string \texttt{str} is null,
   it returns the string ``null''.
\end{tabb}
\begin{htmlonly}
   \param{str}{the string to process}
   \return{the same string}
\end{htmlonly}
\begin{code}

   public static String s (int fieldwidth, String str)\begin{hide} {
      if (str == null)
         return s (fieldwidth, "null");

      int fw = Math.abs (fieldwidth);
      if (str.length() < fw) {
         // We have to pad with spaces
         StringBuffer buf = new StringBuffer();
         int sl = str.length();
         for (int i = 0; i < fw-sl; i++)
            buf.append (' ');
         // Add the spaces before or after
         return fieldwidth >= 0 ? buf.toString() + str
                     : str + buf.toString();
      }
      else
         return str;
   }\end{hide}
\end{code}
\begin{tabb} Formats the string \texttt{str} like the \texttt{\%s} in the C \texttt{printf}
 function. The \texttt{fieldwidth} argument gives the minimum length of the
 resulting string.  If \texttt{str} is shorter than \texttt{fieldwidth}, it is
left-padded with spaces.  If \texttt{fieldwidth} is negative, the string
is right-padded with spaces if necessary.  The \class{String} will never
be truncated. If \texttt{str} is null, it calls
\method{s}{int, String}~\texttt{(fieldwidth, ``null'')}.
%
The \texttt{fieldwidth} argument
has the same effect for the other methods in this class.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{str}{the string to process}
   \return{the same string padded with spaces if necessary}
\end{htmlonly}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Integers}
\begin{code}

   public static String d (long x)\begin{hide} {
        return d (0, 1, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{d}{int,int,long}~\texttt{(0, 1, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the string to process}
   \return{the same string, padded with spaces or zeros if appropriate}
\end{htmlonly}
\begin{code}

   public static String d (int fieldwidth, long x)\begin{hide} {
        return d (fieldwidth, 1, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{d}{int,int,long}~\texttt{(fieldwidth, 1, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the string to process}
   \return{the same string, padded with spaces or zeros if appropriate}
\end{htmlonly}
\begin{code}

   public static String d (int fieldwidth, int precision, long x)\begin{hide} {
        if (precision < 0)
            throw new IllegalArgumentException ("precision must " +
                                               "not be negative.");
        if (precision == 0 && x == 0)
            return s (fieldwidth, "");

        nf.setGroupingUsed (false);
        nf.setMinimumIntegerDigits (precision);
        nf.setMaximumFractionDigits (0); // will also set the min to 0
        return s (fieldwidth, nf.format (x));
   }\end{hide}
\end{code}
\begin{tabb} Formats the long integer \texttt{x} into a string like \texttt{\%d}
in the C \texttt{printf} function.  It converts its argument to decimal
notation, \texttt{precision} gives the minimum
number of digits that must appear; if the converted
value  requires  fewer  digits, it is padded on the
left with zeros.  When
zero is printed with an explicit precision 0, the
output is empty.
%
%If the one-argument form is used, a \texttt{fieldwidth} of 0
%is assumed and a \texttt{precision} of 1 is used.
%If the two-arguments method is used, a \texttt{precision} of 1 is assumed.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of digits in the returned string}
   \param{x}{the string to process}
   \return{the same string, padded with spaces or zeros if appropriate}
\end{htmlonly}
\begin{code}

   public static String format (long x)\begin{hide} {
      return d (0, 1, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{d}{int,int,long}~\texttt{(0, 1, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be processed}
   \return{the string resulting from the conversion}
\end{htmlonly}
\begin{code}

   public static String format (int fieldwidth, long x)\begin{hide} {
      return d (fieldwidth, 1, x);
   }\end{hide}
\end{code}
\begin{tabb} Converts a long integer to a \class{String} with a minimum length
of \texttt{fieldwidth}, the result is right-padded with spaces if
necessary but it is not truncated.  If only one argument is specified,
a \texttt{fieldwidth} of 0 is assumed.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be processed}
   \return{the string resulting from the conversion}
\end{htmlonly}
\begin{code}

   public static String formatBase (int b, long x)\begin{hide} {
      return formatBase (0, b, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{formatBase}{int,int,long}~\texttt{(0, b, x)}.
\end{tabb}
\begin{htmlonly}
   \param{b}{the base used for conversion}
   \param{x}{the value to be processed}
   \return{a string representing \texttt{x} in base \texttt{b}}
\end{htmlonly}\begin{code}

   public static String formatBase (int fieldwidth, int b, long x)\begin{hide} {
      boolean neg = false;                   // insert a '-' if true
      if (b < 2 || b > 10)
         throw new IllegalArgumentException ("base must be between 2 and 10.");

      if (x < 0) {
         neg = true;
         x = -x;
      } else {
         if (x == 0)
            return "0";

         neg = false;
      }
      StringBuffer sb = new StringBuffer();
      while (x > 0) {
         sb.insert(0, x % b);
         x = x/b;
      }
      if (neg)
         sb.insert(0, '-');
      return s (fieldwidth, sb.toString());
   }\end{hide}
\end{code}
\begin{tabb} Converts the integer \texttt{x} to a \class{String} representation in base
\texttt{b}. Restrictions: $2\le$ \texttt{b} $\le 10$.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{b}{the base used for conversion}
   \param{x}{the value to be processed}
   \return{a string representing \texttt{x} in base \texttt{b}}
\end{htmlonly}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Reals}
\begin{code}

   public static String E (double x)\begin{hide} {
        return E (0, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{E}{int,int,double}~\texttt{(0, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String E (int fieldwidth, double x)\begin{hide} {
        return E (fieldwidth, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{E}{int,int,double}~\texttt{(fieldwidth, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String E (int fieldwidth, int precision, double x)\begin{hide} {
        if (precision < 0)
            throw new IllegalArgumentException ("precision must " +
                                               "not be negative.");
        if (Double.isNaN (x))
           return s (fieldwidth, "NaN");
        if (Double.isInfinite (x))
           return s (fieldwidth, (x < 0 ? "-" : "") + "Infinite");

        DecimalFormat df;
        if (precision >= dfe.length || dfe[precision] == null) {
          // We need to create one pattern per precision value
          StringBuffer pattern = new StringBuffer ("0.");
          for (int i = 0; i < precision; i++)
              pattern.append ("0");
          pattern.append ("E00");
          df = new DecimalFormat (pattern.toString(), dfs);
          df.setGroupingUsed (false);
          if (precision < dfe.length)
            dfe[precision] = df;
        }
        else
          df = dfe[precision];
        String res = df.format (x);
        // DecimalFormat doesn't add the + sign before the value of
        // the exponent.
        int exppos = res.indexOf ('E');
        if (exppos != -1 && res.charAt (exppos+1) != '-')
            res = res.substring (0, exppos+1) + "+" + res.substring (exppos+1);
        return s (fieldwidth, res);
   }\end{hide}
\end{code}
\begin{tabb} Formats a double-precision number \texttt{x} like \texttt{\%E} in C {\tt
printf}.  The double argument is rounded and converted in the
style \texttt{[-]d.dddE+-dd} where there is one digit  before
the  decimal-point character and the number of digits
after it is equal to the precision;
if the precision is 0, no decimal-point character appears.
The  exponent  always
contains at least two digits; if the value is zero,
the exponent is \texttt{00}.
%
%If the one-argument form is used, a \texttt{fieldwidth} of 0 and
%a \texttt{precision} of 6 are used.
%If the two-arguments form is used, a \texttt{precision} of 6 is assumed.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of digits after the decimal point}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String e (double x)\begin{hide} {
        return e (0, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{e}{int,int,double}~\texttt{(0, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String e (int fieldwidth, double x)\begin{hide} {
        return e (fieldwidth, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{e}{int,int,double}~\texttt{(fieldwidth, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String e (int fieldwidth, int precision, double x)\begin{hide} {
        String res = E (fieldwidth, precision, x);
        int exppos = res.indexOf ('E');
        return exppos == -1 ? res : res.substring (0,
                               exppos) + 'e' + res.substring (exppos+1);
   }\end{hide}
\end{code}
\begin{tabb} The same as \texttt{E}, except that \texttt{`e'} is used as the exponent
character instead of \texttt{`E'}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of digits after the decimal point}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String f (double x)\begin{hide} {
        return f (0, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{f}{int,int,double}~\texttt{(0, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String f (int fieldwidth, double x)\begin{hide} {
        return f (fieldwidth, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{f}{int,int,double}~\texttt{(fieldwidth, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String f (int fieldwidth, int precision, double x)\begin{hide} {
        if (precision < 0)
            throw new IllegalArgumentException ("precision must " +
                                               "not be negative.");
        if (Double.isNaN (x))
           return s (fieldwidth, "NaN");
        if (Double.isInfinite (x))
           return s (fieldwidth, (x < 0 ? "-" : "" ) + "Infinite");

        nf.setGroupingUsed (false);
        nf.setMinimumIntegerDigits (1);
        nf.setMinimumFractionDigits (precision);
        nf.setMaximumFractionDigits (precision);
        return s (fieldwidth, nf.format (x));
   }\end{hide}
\end{code}
\begin{tabb} Formats the double-precision \texttt{x} into a string like
\texttt{\%f} in  C \texttt{printf}.
The argument is  rounded  and  converted to
decimal notation in the style \texttt{[-]ddd.ddd}, where the
number of digits after the decimal-point character
is  equal  to  the precision specification.
If the precision is explicitly 0, no decimal-point
character appears.  If a decimal point appears, at least
one digit appears before it.
%
%If the one-argument form is used, a \texttt{fieldwidth} of 0 and a
%\texttt{precision} of 6 are used.
%If the two-arguments form is used, a \texttt{precision} of 6 is assumed.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of digits after the decimal point}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String G (double x)\begin{hide} {
        return G (0, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{G}{int,int,double}~\texttt{(0, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String G (int fieldwidth, double x)\begin{hide} {
        return G (fieldwidth, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{G}{int,int,double}~\texttt{(fieldwidth, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String G (int fieldwidth, int precision, double x)\begin{hide} {
        if (precision < 0)
            throw new IllegalArgumentException ("precision must " +
                                               "not be negative.");
        if (precision == 0)
            precision = 1;

        if (Double.isNaN (x))
           return s (fieldwidth, "NaN");
        if (Double.isInfinite (x))
           return s (fieldwidth, (x < 0 ? "-" : "" ) + "Infinite");

        // Calculate the scientific notation format.
        // We cannot use E because it can make trailing zeros
        // that must be removed afterward.
        DecimalFormat df;
        if (precision >= dfg.length || dfg[precision] == null) {
          StringBuffer pattern = new StringBuffer ("0.");
          for (int i = 0; i < (precision-1); i++)
              pattern.append ("#"); // Do not show trailing zeros
          pattern.append ("E00");
          df = new DecimalFormat (pattern.toString(), dfs);
          df.setGroupingUsed (false);
          if (precision < dfg.length)
            dfg[precision] = df;
        }
        else
          df = dfg[precision];
        String res = df.format (x);

        int exppos = res.indexOf ('E');
        if (exppos == -1)
           return res;
        int expval = Integer.parseInt (res.substring (exppos+1));
        if (expval < -4 || expval >= precision) {
           // add the plus sign for the exponent if necessary.
           if (res.charAt (exppos+1) != '-')
               return s (fieldwidth, res.substring (0, exppos+1) + "+" +
                          res.substring (exppos+1));
           else
               return s (fieldwidth, res);
        }

        // Calculate the decimal notation format
        nf.setGroupingUsed (false);
        nf.setMinimumIntegerDigits (1);
        nf.setMinimumFractionDigits (0);
        // We need the number of digits after the decimal point to
        // to get precisions significant digits.
        // The integer part of x contains at most precision digits.
        // If that was not true, expval would be greater than precision.
        // If expval=0, we have a number of the form 1.234...
        // To have precisions significant digits, we need precision-1 digits.
        // If expval<0, x<1 and we need -expval additionnal
        // decimal digits.
        // If expval>0, we need less decimal digits.
        nf.setMaximumFractionDigits (precision-expval-1);
        res = nf.format (x);
        return s (fieldwidth, res);
   }\end{hide}
\end{code}
\begin{tabb} Formats the double-precision \texttt{x} into a string like
\texttt{\%G} in C \texttt{printf}.
The argument is converted in style \texttt{\%f} or \texttt{\%E}.
\texttt{precision} specifies
the number of significant digits.  If it is
0,  it  is treated as 1.  Style \texttt{\%E} is used if the
exponent from its conversion is less than $-4$ or
greater than or equal to \texttt{precision}.  Trailing
zeros are removed from the fractional part of the
result; a decimal point appears only if it is followed
by at least one digit.
%
%If the one-argument form is used, a \texttt{fieldwidth} of 0 and
%a \texttt{precision} of 6 are used.
%If the two-arguments form is used, a \texttt{precision} of 6 is assumed.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of significant digits}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String g (double x)\begin{hide} {
        return g (0, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{g}{int,int,double}~\texttt{(0, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String g (int fieldwidth, double x)\begin{hide} {
        return g (fieldwidth, 6, x);
   }\end{hide}
\end{code}
\begin{tabb}   Same as \method{g}{int,int,double}~\texttt{(fieldwidth, 6, x)}.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String g (int fieldwidth, int precision, double x)\begin{hide} {
        String res = G (fieldwidth, precision, x);
        int exppos = res.indexOf ('E');
        return exppos == -1 ? res :
            res.substring (0, exppos) + 'e' + res.substring (exppos+1);
   }\end{hide}
\end{code}
\begin{tabb} The same as \texttt{G}, except that \texttt{`e'} is used in the scientific
notation.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{precision}{number of significant digits}
   \param{x}{the value to be converted to string}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String format (int fieldwidth, int accuracy, int precision,
                                double x)\begin{hide} {
        if (Double.isNaN (x))
           return s (fieldwidth, "NaN");
        if (Double.isInfinite (x))
           return s (fieldwidth, (x < 0 ? "-" : "" ) + "Infinite");

       if (canUseDecimalNotation (fieldwidth, accuracy, precision, x))
          return f (fieldwidth, accuracy, x);
       // Use scientific notation
       else {
          String S = E (fieldwidth, precision - 1 , x);
          return processExp (S);
       }
   }

   private static boolean canUseDecimalNotation (int fieldwidth, int accuracy,
                                                 int precision, double x) {
      // Le nombre de positions occupees par la partie entiere de x
      int PosEntier = 0;
      // Le nombre de chiffres significatifs avant le point
      int EntierSign;
      // La position de l'exposant dans le string S et la longueur de S
      int Neg = 0;

      if (x == 0.0)
         EntierSign = 1;
      else {
         EntierSign = PosEntier = (int)Math.floor (
               Math.log10 (Math.abs (x)) + 1);
         if (x < 0.0)
             Neg = 1;
      }
      if (EntierSign <= 0)
          PosEntier = 1;
      return x == 0.0 || (((EntierSign + accuracy) >= precision) &&
                          (fieldwidth >= (PosEntier + accuracy + Neg + 1)));
   }

   private static int getMinAccuracy (double x) {
      if (Math.abs (x) >= 1 || x == 0)
         return 0;
      else
         return -(int)Math.floor (Math.log10 (Math.abs (x)));
   }

   private static String processExp (String s) {
      int p = s.indexOf ("E+0");
      if (p == -1)
         p = s.indexOf ("E-0");

      // remove the 0 in E-0 and in E+0
      if (p != -1)
         s = " " + s.substring (0, p + 2) + s.substring (p + 3);

      p = s.indexOf (".E");
      if (p != -1)
         s = " " + s.substring (0, p) + s.substring (p + 1);
      return s;
   }\end{hide}
\end{code}
\begin{tabb}
   Returns a \class{String} containing \texttt{x}.  Uses a total of at least
   \texttt{fieldwidth} positions (including the sign and point when they appear),
   \texttt{accuracy} digits after the decimal point and at least \texttt{precision}
   significant digits. \texttt{accuracy} and \texttt{precision} must be strictly
   smaller than \texttt{fieldwidth}. The number is rounded if necessary.
   If there is not enough space to format the number in decimal notation
   with at least \texttt{precision} significant digits (\texttt{accuracy} or
   \texttt{fieldwidth} is too small), it will be converted to scientific
   notation with at least \texttt{precision} significant digits.
   In that case, \texttt{fieldwidth} is increased if necessary.
  \end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{accuracy}{number of digits after the decimal point}
   \param{precision}{number of significant digits}
   \param{x}{the value to be processed}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String format (Locale locale, int fieldwidth, int accuracy,
                                int precision, double x)\begin{hide} {
         Formatter fmt = new Formatter (locale);
        if (Double.isNaN (x))
           return fmt.format ("%" + fieldwidth + "s", "NaN").toString();
        if (Double.isInfinite (x))
           return fmt.format ("%" + fieldwidth + "s", (x < 0 ? "-" : "" ) + "Infinite").toString();

       if (canUseDecimalNotation (fieldwidth, accuracy, precision, x))
          return fmt.format ("%" + fieldwidth + "." + accuracy + "f", x).toString();
       // Use scientific notation
       else {
          String S = fmt.format ("%" + fieldwidth + "." + (precision - 1) + "E", x).toString();
          return processExp (S);
       }
   }\end{hide}
\end{code}
\begin{tabb}
  This method is equivalent to
  \method{format}{int,int,int,double}, except it formats the given
  value for the locale \texttt{locale}.
    \end{tabb}
\begin{htmlonly}
  \param{locale}{the locale being used for formatting}
   \param{fieldwidth}{minimum length of the returned string}
   \param{accuracy}{number of digits after the decimal point}
   \param{precision}{number of significant digits}
   \param{x}{the value to be processed}
   \return{the converted value as a string}
\end{htmlonly}
\begin{code}

   public static String formatBase (int fieldwidth, int accuracy, int b,
                                    double x)\begin{hide} {
      if (Double.isNaN (x))
         return s (fieldwidth, "NaN");
      if (Double.isInfinite (x))
         return s (fieldwidth, (x < 0 ? "-" : "" ) + "Infinite");
      if (0. == x || -0. == x)
         return s (fieldwidth, "0");
      if (Math.abs(x) >= Num.TWOEXP[63])
         throw new UnsupportedOperationException ("   |x| >= 2^63");

      long n = (long) x;
      String mant = formatBase(-1, b, n);
      if (n == x)
         return s (fieldwidth, mant);
      if (n == 0) {
         if (x < 0) {
            mant = "-0";
         } else
            mant = "0";
      }
      // round before printing
      if (x > 0)
         x += 0.5*Math.pow(b, -accuracy - 1);
      else if (x < 0)
         x -= 0.5*Math.pow(b, -accuracy - 1);
       x -= n;
      if (x < 0)
         x = -x;

      StringBuffer frac = new StringBuffer(".");
      long y;
      int j;
      for (j = 0; j < accuracy; ++j) {
         x *= b;
         y = (long) x;
         frac.append(y);
         x -= y;
         if (x == 0.)
            break;
      }

      StringBuffer number = new StringBuffer(mant);
      number.append(frac);

      // remove trailing spaces and 0
      j = number.length() - 1;
      while (j > 0 && (number.charAt(j) == '0' || number.charAt(j) == ' ' )) {
         number.deleteCharAt(j);
         j--;
      }

      return s (fieldwidth, number.toString());
   }\end{hide}
\end{code}
\begin{tabb}
Converts $x$ to a String representation in base $b$ using formatting similar
to the $f$ methods. Uses a total of at least \texttt{fieldwidth} positions
(including the sign and point when they appear) and \texttt{accuracy} digits
 after the decimal point. If \texttt{fieldwidth} is negative, the number is
  printed  left-justified, otherwise right-justified.
  Restrictions: $2 \le  b  \le 10$ and $|x| < 2^{63}$.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the returned string}
   \param{accuracy}{number of digits after the decimal point}
   \param{b}{base}
   \param{x}{the value to be processed}
   \return{the converted value as a string}
\end{htmlonly}
%
\begin{hide}\begin{code}
   // Interface CharSequence
   public char charAt (int index) {
      return sb.charAt (index);
   }

   public int length() {
      return sb.length();
   }

   public CharSequence subSequence (int start, int end) {
      return sb.subSequence (start, end);
   }

   // Interface Appendable
   public Appendable append (CharSequence csq) {
      return sb.append (csq);
   }

   public Appendable append (CharSequence csq, int start, int end) {
      return sb.append (csq, start, end);
   }
\end{code}\end{hide}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Intervals}
\begin{code}

   public static void formatWithError (int fieldwidth, int fieldwidtherr,
          int accuracy, int precision, double x, double error, String[] res)\begin{hide} {
      if (res.length != 2)
         throw new IllegalArgumentException ("The given res array must contain two elements");
      if (Double.isNaN (x)) {
         res[0] = s (fieldwidth, "NaN");
         res[1] = s (fieldwidtherr, "");
         return;
      }
      if (Double.isInfinite (x)) {
         res[0] = s (fieldwidth, (x < 0 ? "-" : "" ) + "Infinite");
         res[1] = s (fieldwidtherr, "");
         return;
      }
      if (accuracy < 0)
         accuracy = 0;

      if (canUseDecimalNotation (fieldwidth, accuracy, precision, x)) {
         res[0] = f (fieldwidth, accuracy, x);
         res[1] = f (fieldwidtherr, accuracy, error);
      }
      // Use scientific notation
      else {
         res[0] = processExp (E (fieldwidth, precision - 1, x));
         int xExp = x == 0 ? 0 : (int)Math.floor (Math.log10 (Math.abs (x)));
         int errorExp = error == 0 ? 0 : (int)Math.floor (Math.log10 (Math.abs (error)));
         int errorPrecision = precision - 1 - (xExp - errorExp);
         if (errorPrecision < 0)
            errorPrecision = 0;
         res[1] = processExp (E (fieldwidtherr, errorPrecision, error));
      }
   }\end{hide}
\end{code}
\begin{tabb}
   Stores a string containing \texttt{x} into \texttt{res[0]}, and
   a string containing \texttt{error} into \texttt{res[1]}, both strings being
   formatted with the same notation.
   Uses a total of at least
   \texttt{fieldwidth} positions (including the sign and point when they appear)
   for \texttt{x}, \texttt{fieldwidtherr} positions for \texttt{error},
   \texttt{accuracy} digits after the decimal point and at least \texttt{precision}
   significant digits. \texttt{accuracy} and \texttt{precision} must be strictly
   smaller than \texttt{fieldwidth}. The numbers are rounded if necessary.
   If there is not enough space to format \texttt{x} in decimal notation
   with at least \texttt{precision} significant digits (\texttt{accuracy} or
   \texttt{fieldwidth} are too small), it will be converted to scientific
   notation with at least \texttt{precision} significant digits.
   In that case, \texttt{fieldwidth} is increased if necessary, and
   the error is also formatted in scientific notation.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the value string}
   \param{fieldwidtherr}{minimum length of the error string}
   \param{accuracy}{number of digits after the decimal point for the value and error}
   \param{precision}{number of significant digits for the value}
   \param{x}{the value to be processed}
   \param{error}{the error on the value to be processed}
   \param{res}{an array that will be filled with the formatted value and formatted error}
\end{htmlonly}
\begin{code}

   public static void formatWithError (int fieldwidth, int fieldwidtherr,
          int precision, double x, double error, String[] res)\begin{hide} {
      int accuracy = getMinAccuracy (error);
      if (!canUseDecimalNotation (fieldwidth, accuracy, precision, x)) {
         int posEntier = (int)Math.floor (Math.log (Math.abs (x)) / Math.log (10) + 1);
         if (posEntier < 0)
            posEntier = 1;
         int newAccuracy = precision - posEntier;
         if (canUseDecimalNotation (fieldwidth, newAccuracy, precision, x))
            accuracy = newAccuracy;
      }
      formatWithError (fieldwidth, fieldwidtherr, accuracy, precision, x, error, res);
   }\end{hide}
\end{code}
\begin{tabb}
   Stores a string containing \texttt{x} into \texttt{res[0]}, and
   a string containing \texttt{error} into \texttt{res[1]}, both strings being
   formatted with the same notation.
   This calls \method{formatWithError}{int,int,int,int,double,double,String[]} with
   the minimal accuracy for which the formatted string for \texttt{error} is non-zero.
   If \texttt{error} is 0, the accuracy is 0.
   If this minimal accuracy causes the strings to be formatted using scientific
   notation, this method increases the accuracy until the decimal notation can be used.
\end{tabb}
\begin{htmlonly}
   \param{fieldwidth}{minimum length of the value string}
   \param{fieldwidtherr}{minimum length of the error string}
   \param{precision}{number of significant digits for the value}
   \param{x}{the value to be processed}
   \param{error}{the error on the value to be processed}
   \param{res}{an array that will be filled with the formatted value and formatted error}
\end{htmlonly}
\begin{code}

   public static void formatWithError (Locale locale, int fieldwidth,
          int fieldwidtherr, int accuracy, int precision, double x,
          double error, String[] res)\begin{hide} {
      if (res.length != 2)
         throw new IllegalArgumentException ("The given res array must contain two elements");
      Formatter fmt = new Formatter (locale);
      Formatter fmtErr = new Formatter (locale);
      if (Double.isNaN (x)) {
         res[0] = fmt.format ("%" + fieldwidth + "s", "NaN").toString();
         res[1] = fmtErr.format ("%" + fieldwidtherr + "s", "").toString();
         return;
      }
      if (Double.isInfinite (x)) {
         res[0] = fmt.format ("%" + fieldwidth + "s", (x < 0 ? "-" : "" ) + "Infinite").toString();
         res[1] = fmtErr.format ("%" + fieldwidtherr + "s", "").toString();
         return;
      }
      if (accuracy < 0)
         accuracy = 0;

      if (canUseDecimalNotation (fieldwidth, accuracy, precision, x)) {
         res[0] = fmt.format ("%" + fieldwidth + "." + accuracy + "f", x).toString();
         res[1] = fmtErr.format ("%" + fieldwidtherr + "." + accuracy + "f", error).toString();
      }
      // Use scientific notation
      else {
         res[0] = processExp (fmt.format ("%" + fieldwidth + "." + (precision - 1) + "E", x).toString());
         int xExp = x == 0 ? 0 : (int)Math.floor (Math.log10 (Math.abs (x)));
         int errorExp = error == 0 ? 0 : (int)Math.floor (Math.log10 (Math.abs (error)));
         int errorPrecision = precision - 1 - (xExp - errorExp);
         if (errorPrecision < 0)
            errorPrecision = 0;
         res[1] = processExp (fmtErr.format
         ("%" + fieldwidtherr + "." + errorPrecision + "E", error).toString());
      }
   }\end{hide}
\end{code}
\begin{tabb}
  This method is equivalent to
  \method{formatWithError}{int,int,int,double,double,String[]},
  except that it formats the given value and error for the
  locale \texttt{locale}.
\end{tabb}
\begin{htmlonly}
  \param{locale}{the locale being used}
   \param{fieldwidth}{minimum length of the value string}
   \param{fieldwidtherr}{minimum length of the error string}
   \param{accuracy}{number of digits after the decimal point for the value and error}
   \param{precision}{number of significant digits for the value}
   \param{x}{the value to be processed}
   \param{error}{the error on the value to be processed}
   \param{res}{an array that will be filled with the formatted value and formatted error}
\end{htmlonly}
\begin{code}

   public static void formatWithError (Locale locale, int fieldwidth,
          int fieldwidtherr, int precision, double x, double error,
          String[] res)\begin{hide} {
      int accuracy = getMinAccuracy (error);
      if (!canUseDecimalNotation (fieldwidth, accuracy, precision, x)) {
         int posEntier = (int)Math.floor (Math.log (Math.abs (x)) / Math.log (10) + 1);
         if (posEntier < 0)
            posEntier = 1;
         int newAccuracy = precision - posEntier;
         if (canUseDecimalNotation (fieldwidth, newAccuracy, precision, x))
            accuracy = newAccuracy;
      }
      formatWithError (locale, fieldwidth, fieldwidtherr, accuracy, precision, x, error, res);
   }\end{hide}
\end{code}
\begin{tabb}
  This method is equivalent to
  \method{formatWithError}{int,int,int,double,double,String[]},
  except that it formats the given value and error for the
  locale \texttt{locale}.
\end{tabb}
\begin{htmlonly}
   \param{locale}{the locale being used}
   \param{fieldwidth}{minimum length of the value string}
   \param{fieldwidtherr}{minimum length of the error string}
   \param{precision}{number of significant digits for the value}
   \param{x}{the value to be processed}
   \param{error}{the error on the value to be processed}
   \param{res}{an array that will be filled with the formatted value and formatted error}
\end{htmlonly}
%
\begin{code}\begin{hide}
}\end{hide}
\end{code}
